//package com.ptkc.web;
//
//import com.ptkc.constants.Page;
//import com.ptkc.constants.WebResult;
//import com.ptkc.data.entity.SellRecordStatistical;
//import com.ptkc.data.model.Order;
//import com.ptkc.data.repository.OrderIRepository;
//import com.ptkc.utils.StringUtil;
//import org.elasticsearch.action.search.SearchResponse;
//import org.elasticsearch.action.search.SearchType;
//import org.elasticsearch.index.query.BoolQueryBuilder;
//import org.elasticsearch.index.query.QueryBuilders;
//import org.elasticsearch.search.aggregations.AggregationBuilder;
//import org.elasticsearch.search.aggregations.AggregationBuilders;
//import org.elasticsearch.search.aggregations.Aggregations;
//import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder;
//import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
//import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
//import org.elasticsearch.search.aggregations.bucket.terms.InternalTerms;
//import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
//import org.elasticsearch.search.aggregations.metrics.sum.Sum;
//import org.elasticsearch.search.aggregations.metrics.sum.SumAggregationBuilder;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.domain.Pageable;
//import org.springframework.data.elasticsearch.annotations.Document;
//import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
//import org.springframework.data.elasticsearch.core.ResultsExtractor;
//import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
//import org.springframework.data.web.PageableDefault;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//import javax.servlet.http.HttpServletRequest;
//import java.math.BigDecimal;
//import java.text.ParsePosition;
//import java.text.SimpleDateFormat;
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.List;
//
///**
// * @author: Mr.Jiao
// * @date: 2018年11月07日
// */
//@RestController
//@RequestMapping(value = "/order")
//public class OrderController {
//
//    @Autowired
//    private OrderIRepository repository;
//
//    @Autowired
//    private ElasticsearchTemplate template;
//
//    @GetMapping(value = "/search")
//    public WebResult<Page<Order>> getOrders(HttpServletRequest request, @PageableDefault Pageable pageable){
//        String[] agents = request.getParameterValues("agents");
//        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//        if(agents != null && agents.length > 0){
//            boolQueryBuilder.must(QueryBuilders.termsQuery("agentId", agents));
//        }
//        String orderNo = request.getParameter("orderNo");
//        if(StringUtil.isNotEmpty(orderNo)){
//            boolQueryBuilder.must(QueryBuilders.termQuery("orderCode", orderNo));
//        }
//        String busId = request.getParameter("busId");
//        if(busId != null){
//            boolQueryBuilder.must(QueryBuilders.termQuery("businessId", busId));
//        }
//        String userMobile = request.getParameter("mobile");
//        if(StringUtil.isNotEmpty(userMobile)){
//            boolQueryBuilder.must(QueryBuilders.termQuery("userMobile", userMobile));
//        }
//        String busName = request.getParameter("busName");
//        if(StringUtil.isNotEmpty(busName)){
//            boolQueryBuilder.must(QueryBuilders.prefixQuery("businessName", busName));
//        }
//        String starttime = request.getParameter("starttime");
//        String endtime = request.getParameter("endtime");
//        if(starttime != null && starttime.matches("14\\d{11}\\D") && endtime != null && endtime.matches("14\\d{11}\\D")){
//            boolQueryBuilder.must(QueryBuilders.rangeQuery("createTime").from(starttime, true).to(endtime, true));
//        }
//        String status = request.getParameter("status");
//        if(status != null) {
//            switch (status) {
//                case "CANCEL":
//                    boolQueryBuilder.must(QueryBuilders.termQuery("status", "-1"));
//                    break;
//                case "COMPLETE":
//                    boolQueryBuilder.must(QueryBuilders.termQuery("status", "8"));
//                    break;
//                case "UNDERWAY":
//                    boolQueryBuilder.must(QueryBuilders.rangeQuery("status").from("1", true).to("7", true));
//                    break;
//                case "UNRECEIPT":
//                    boolQueryBuilder.must(QueryBuilders.termQuery("status", "1"));
//                    break;
//                default:
//            }
//        }
//        org.springframework.data.domain.Page<Order> orders = repository.search(boolQueryBuilder, pageable);
//        return WebResult.ok(new Page<Order>(orders.getTotalElements(), pageable.getPageNumber(), pageable.getPageSize(), orders.getContent()));
//    }
//
//    /**
//     * 统计
//     * @return
//     */
//    @GetMapping(value = "/statistical")
//    public WebResult<List<SellRecordStatistical>> getStatistical(HttpServletRequest request){
//        String agentsStr = request.getParameter("agents");
//        Integer[] agents = StringUtil.split(agentsStr);
//        String starttime = request.getParameter("starttime");
//        String endtime = request.getParameter("endtime");
//
//        String timeFormatPattern = "yyyy-MM-dd HH";
//        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
//        BoolQueryBuilder qbs = QueryBuilders.boolQuery();
//        if(agents != null && agents.length > 0){
//            qbs.must(QueryBuilders.termsQuery("agentId", agents));
//        }
//        if(starttime != null && starttime.matches("14\\d{11}\\D") && endtime != null && endtime.matches("14\\d{11}\\D")){
//            qbs.must(QueryBuilders.rangeQuery("createTime").from(starttime, true).to(endtime, true));
//        }
//        //完成的订单
//        qbs.must(QueryBuilders.termQuery("status", 8));
//        nativeSearchQueryBuilder.withQuery(qbs);
//        Document document = Order.class.getAnnotation(Document.class);
//        nativeSearchQueryBuilder.withSearchType(SearchType.DEFAULT);
//        nativeSearchQueryBuilder.withIndices(document.indexName()).withTypes(document.type());
//
//        DateHistogramAggregationBuilder timeBuilder = AggregationBuilders.dateHistogram("agg_create_time").field("createTime").dateHistogramInterval(DateHistogramInterval.hours(1)).format(timeFormatPattern);
//        TermsAggregationBuilder payTypeBuilder = AggregationBuilders.terms("agg_pay_type").field("payType");
//        TermsAggregationBuilder isDeliverBuilder = AggregationBuilders.terms("agg_is_deliver").field("isDeliver");
//        TermsAggregationBuilder loginOnBuilder = AggregationBuilders.terms("agg_login_on").field("loginOn");
//        //聚合查询
//        SumAggregationBuilder totalPay = AggregationBuilders.sum("agg_totalpay").field("totalpay");
//        SumAggregationBuilder totalRefund = AggregationBuilders.sum("agg_refund").field("refund");
//        SumAggregationBuilder goodsTotal = AggregationBuilders.sum("agg_goods_total").field("goodsTotal");
//        SumAggregationBuilder activityprice = AggregationBuilders.sum("agg_activityprice").field("activityprice");
//        SumAggregationBuilder subsidy = AggregationBuilders.sum("agg_subsidy").field("subsidy");
//        SumAggregationBuilder showps = AggregationBuilders.sum("agg_showps").field("showps");
//        SumAggregationBuilder agentBusget = AggregationBuilders.sum("agg_agent_busget").field("agentBusget");
//
//        AggregationBuilder aggregationBuilder = totalPay.subAggregation(totalRefund).subAggregation(goodsTotal).subAggregation(activityprice).subAggregation(subsidy).subAggregation(showps).subAggregation(agentBusget);
//
//        nativeSearchQueryBuilder.addAggregation(timeBuilder.subAggregation(payTypeBuilder.subAggregation(isDeliverBuilder.subAggregation(loginOnBuilder.subAggregation(aggregationBuilder)))));
//        Aggregations agg = template.query(nativeSearchQueryBuilder.build(), new ResultsExtractor<Aggregations>() {
//            @Override
//            public Aggregations extract(SearchResponse response) {
//                return response.getAggregations();
//            }
//        });
//        if(agg == null){
//            return WebResult.fail("查询失败");
//        }else{
//            List<SellRecordStatistical> recordStatisticals = new ArrayList<>();
//            Histogram histogram = agg.get("agg_create_time");
//            SimpleDateFormat dateFormat = new SimpleDateFormat(timeFormatPattern);
//            for (Histogram.Bucket entry : histogram.getBuckets()) {
//                String timer = entry.getKeyAsString();
//                ParsePosition pos = new ParsePosition(0);
//                //订单时间(记录到小时)
//                Date orderHour = dateFormat.parse(timer, pos);
//                InternalTerms payTypTerms = entry.getAggregations().get("agg_pay_type");
//                List<InternalTerms.Bucket> payTypeBuckets = payTypTerms.getBuckets();
//                for(InternalTerms.Bucket pbucket : payTypeBuckets){
//                    //支付方式
//                    int paytype = pbucket.getKeyAsNumber().intValue();
//                    InternalTerms delyverLongTerms = pbucket.getAggregations().get("agg_is_deliver");
//                    List<InternalTerms.Bucket> deliverBuckets = delyverLongTerms.getBuckets();
//                    for(InternalTerms.Bucket deliverBucket : deliverBuckets){
//                        //配送方式
//                        int deliver = deliverBucket.getKeyAsNumber().intValue();
//                        InternalTerms loginOnTerms = deliverBucket.getAggregations().get("agg_login_on");
//                        List<InternalTerms.Bucket> loginOnBuckets = loginOnTerms.getBuckets();
//                        for(InternalTerms.Bucket bucket : loginOnBuckets){
//                            //登陆方式
//                            int loginOn = bucket.getKeyAsNumber().intValue();
//                            Sum agg_totalpay = bucket.getAggregations().get("agg_totalpay");
//                            Sum agg_refund = bucket.getAggregations().get("agg_refund");
//                            Sum agg_goods_total = bucket.getAggregations().get("agg_goods_total");
//                            Sum agg_activityprice = bucket.getAggregations().get("agg_activityprice");
//                            Sum agg_subsidy = bucket.getAggregations().get("agg_subsidy");
//                            Sum agg_showps = bucket.getAggregations().get("agg_showps");
//                            Sum agg_agent_busget = bucket.getAggregations().get("agg_agent_busget");
//
//                            SellRecordStatistical statistical = new SellRecordStatistical();
//                            statistical.setTime(orderHour);
//                            statistical.setActivityprice(BigDecimal.valueOf(agg_activityprice.getValue()));
//                            statistical.setAgentBusget(BigDecimal.valueOf(agg_agent_busget.getValue()));
//                            statistical.setGoodstotal((int) agg_goods_total.getValue());
//                            statistical.setRefund(BigDecimal.valueOf(agg_refund.getValue()));
//                            statistical.setTotalpay(BigDecimal.valueOf(agg_totalpay.getValue()));
//                            statistical.setSubsidy(BigDecimal.valueOf(agg_subsidy.getValue()));
//                            statistical.setShowps(BigDecimal.valueOf(agg_showps.getValue()));
//                            statistical.setLoginOn(loginOn);
//                            statistical.setIsDeliver(deliver);
//                            statistical.setPaytype(paytype);
//                            statistical.setQuantity((int)bucket.getDocCount());
//                            recordStatisticals.add(statistical);
//                        }
//                    }
//                }
//            }
//            return WebResult.ok("ok", recordStatisticals);
//        }
//    }
//
//
//}
